package com.borimi.demo;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.borimi.demo.bean.UserBinding;
import com.borimi.demo.bean.UserBindingRequest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.sql.SQLException;
import java.time.Duration;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * 微信openid转换器，用于读取本地JSON文件中的openid，调用API进行转换，并保存结果
 */
public class WechatOpenidConverter {
    private static final Logger logger = Logger.getLogger(WechatOpenidConverter.class.getName());
    private static final int MAX_OPENID_PER_REQUEST = 100; // 每次请求最多100个openid
    private static final String API_URL = "https://api.weixin.qq.com/cgi-bin/changeopenid";
    private static final String API_BASIC_URL = "https://api.weixin.qq.com/cgi-bin/user/info/batchget";
           //  +"?access_token=" +
            //"96_5Y1s9piw5FW146A5udo1Mci5t3FKVjMY8YpHOZUhtXMIeTh5_QJK8deH-d_1w5D2SPII7bCRbQqfHh-_76rTp2v5iqILxZGbXx-XXnsFKm82K6toWrGmpnlDx60EIQdABAVZH"; // 替换为实际API地址

    private static final String INPUT_FILE_PATH = "D:\\blmProject\\MyDemo\\src\\main\\java\\com\\borimi\\demo\\old_openID.json"; // 输入文件路径
    private static final String OUTPUT_FILE_PATH = "D:\\blmProject\\MyDemo\\src\\main\\java\\com\\borimi\\demo\\converted_openID.json"; // 输出文件路径
    private static final String OUTPUT_FILE_PATH_JSON = "D:\\blmProject\\MyDemo\\src\\main\\java\\com\\borimi\\demo\\openidMapping.json"; // 输出文件路径
    private static final String OUTPUT_FILE_PATH_SQL = "D:\\blmProject\\MyDemo\\src\\main\\java\\com\\borimi\\demo\\sql\\insert.sql"; // 输出文件路径
    private static final String OUTPUT_FILE_PATH_NEW_SQL = "D:\\blmProject\\MyDemo\\src\\main\\java\\com\\borimi\\demo\\sql\\insert_new.sql"; // 输出文件路径

    private final HttpClient httpClient;
    private final ObjectMapper objectMapper;
    String TOKEN="";


    public WechatOpenidConverter() {
        this.httpClient = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();
        this.objectMapper = new ObjectMapper();
    }

    /**
     * 读取输入文件中的openid列表
     * @return openid列表
     */
    public  JSONArray readOpenidList(String filePath) {


            // 读取JSON数组
        List<Map<String, Object>> dataList = null;
        try {
            dataList = objectMapper.readValue(
                    new File(filePath),
                    new TypeReference<List<Map<String, Object>>>() {}
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String jsonString = JSONObject.toJSONString(dataList);
            return JSONArray.parseArray(jsonString);

    }

    /**
     * 分批调用API转换openid
     * @param openidList 要转换的openid列表
     * @return 转换结果列表
     */
    private List<ConversionResult> convertOpenids(List<String> openidList) {
        List<ConversionResult> results = new ArrayList<>();

        // 分批处理openid列表
        for (int i = 0; i < openidList.size(); i += MAX_OPENID_PER_REQUEST) {
            int end = Math.min(i + MAX_OPENID_PER_REQUEST, openidList.size());
            List<String> batchOpenids = openidList.subList(i, end);

            try {
                String response = sendPostRequest(API_URL,batchOpenids,"wx3d14097dd1c9ee61");
                System.out.println( "请求返回：   "+response);
                logger.log(Level.SEVERE, response);
                List<ConversionResult> batchResults = parseResponse(response);
                results.addAll(batchResults);
                logger.info("Successfully processed batch " + (i/MAX_OPENID_PER_REQUEST + 1));
            } catch (Exception e) {
                logger.log(Level.SEVERE, "Failed to process batch " + (i/MAX_OPENID_PER_REQUEST + 1) + ": " + e.getMessage(), e);
            }
        }

        return results;
    }
    /**
     * 带参数的HTTP GET请求方法
     * @param baseUrl 基础URL
     * @param params 请求参数
     * @param headers 请求头（可选）
     * @return 响应内容
     * @throws IOException IO异常
     * @throws InterruptedException 中断异常
     */
    private String sendGetRequestWithParams(String baseUrl, Map<String, String> params, Map<String, String> headers)
            throws IOException, InterruptedException {

        // 构建带参数的URL
        String urlWithParams = buildUrlWithParams(baseUrl, params);

        // 调用通用GET请求方法
        return sendGetRequest(urlWithParams, headers);
    }

    /**
     * 构建带参数的URL
     * @param baseUrl 基础URL
     * @param params 参数映射
     * @return 带参数的完整URL
     */
    private String buildUrlWithParams(String baseUrl, Map<String, String> params) {
        if (params == null || params.isEmpty()) {
            return baseUrl;
        }

        StringBuilder urlBuilder = new StringBuilder(baseUrl);
        boolean hasQueryParams = baseUrl.contains("?");

        for (Map.Entry<String, String> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();

            if (key != null && value != null) {
                // 如果URL中还没有查询参数，添加?，否则添加&
                urlBuilder.append(hasQueryParams ? "&" : "?");
                hasQueryParams = true;

                // 添加参数（进行URL编码）
                urlBuilder.append(key).append("=").append(java.net.URLEncoder.encode(value, java.nio.charset.StandardCharsets.UTF_8));
            }
        }

        return urlBuilder.toString();
    }

    /**
     * 带参数的HTTP GET请求方法（无请求头）
     * @param baseUrl 基础URL
     * @param params 请求参数
     * @return 响应内容
     * @throws IOException IO异常
     * @throws InterruptedException 中断异常
     */
    private String sendGetRequestWithParams(String baseUrl, Map<String, String> params)
            throws IOException, InterruptedException {
        return sendGetRequestWithParams(baseUrl, params, null);
    }

    /**
     * 通用的HTTP GET请求方法
     * @param url 请求URL
     * @param headers 请求头（可选）
     * @return 响应内容
     * @throws IOException IO异常
     * @throws InterruptedException 中断异常
     */
    private String sendGetRequest(String url, Map<String, String> headers) throws IOException, InterruptedException {
        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .GET()
                .timeout(Duration.ofSeconds(30));

        // 添加请求头
        if (headers != null && !headers.isEmpty()) {
            headers.forEach(requestBuilder::header);
        }

        HttpRequest request = requestBuilder.build();
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

        if (response.statusCode() == 200) {
            return response.body();
        } else {
            throw new RuntimeException("HTTP GET request failed with status code: " + response.statusCode() +
                    ", response: " + response.body());
        }
    }

    /**
     * 通用的HTTP GET请求方法（无请求头）
     * @param url 请求URL
     * @return 响应内容
     * @throws IOException IO异常
     * @throws InterruptedException 中断异常
     */
    private String sendGetRequest(String url) throws IOException, InterruptedException {
        return sendGetRequest(url, null);
    }

    /**
     * 发送POST请求到微信API
     * @param openidList 一批openid列表
     * @return API响应
     * @throws IOException IO异常
     * @throws InterruptedException 中断异常
     */
    private String sendPostRequest(String  url,List<String> openidList,String  fromAppID) throws IOException, InterruptedException {
        // 构造请求体
        Map<String, Object> requestBody = Map.of(
                "from_appid", fromAppID,
                "openid_list", openidList
        );
        String requestBodyJson = objectMapper.writeValueAsString(requestBody);
        Map<String, String> params = new HashMap<>();
        params.put("access_token", TOKEN); // 使用类中的TOKEN变量

        String urlWithToken = buildUrlWithParams(url, params);
        // 构建HTTP请求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(urlWithToken))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(requestBodyJson))
                .build();

        // 发送请求并获取响应
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

        if (response.statusCode() == 200) {
            return response.body();
        } else {
            throw new RuntimeException("HTTP error code: " + response.statusCode() + ", response: " + response.body());
        }
    }
    private String sendPostRequestBatch(String  url,List<UserBindingRequest> openidList,String  fromAppID) throws IOException, InterruptedException {
        // 构造请求体
        Map<String, Object> requestBody = Map.of(
                "user_list", openidList
        );
        String requestBodyJson = objectMapper.writeValueAsString(requestBody);
        Map<String, String> params = new HashMap<>();
        params.put("access_token", TOKEN); // 使用类中的TOKEN变量

        String urlWithToken = buildUrlWithParams(url, params);
        // 构建HTTP请求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(urlWithToken))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(requestBodyJson))
                .build();

        // 发送请求并获取响应
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

        if (response.statusCode() == 200) {
            return response.body();
        } else {
            throw new RuntimeException("HTTP error code: " + response.statusCode() + ", response: " + response.body());
        }
    }
    /**
     * 解析API响应
     * @param responseJson API响应JSON
     * @return 转换结果列表
     * @throws IOException JSON解析异常
     */
    private List<ConversionResult> parseResponse(String responseJson) throws IOException {
        List<ConversionResult> results = new ArrayList<>();
        JsonNode rootNode = objectMapper.readTree(responseJson);

        int errCode = rootNode.path("errcode").asInt();
        String errMsg = rootNode.path("errmsg").asText();

        if (errCode != 0) {
            logger.warning("API request failed with errcode: " + errCode + ", errmsg: " + errMsg);
            // 处理特定错误码
            if (errCode == 63178) {
                logger.warning("from_appid参数错误，和调用的账号并没有迁移关系");
            } else if (errCode == 40001) {
                logger.warning("access_token无效或不是最新的");
            }
            return results;
        }

        // 处理result_list
        JsonNode resultListNode = rootNode.path("result_list");
        if (resultListNode.isArray()) {
            for (JsonNode node : resultListNode) {
                String oriOpenid = node.path("ori_openid").asText();
                String newOpenid = node.path("new_openid").asText();
                String errMsgDetail = node.path("err_msg").asText();

                ConversionResult result = new ConversionResult(oriOpenid, newOpenid, errMsgDetail);
                results.add(result);

                // 记录错误信息
                if (!"ok".equals(errMsgDetail)) {
                    logger.warning("Failed to convert openid " + oriOpenid + ": " + errMsgDetail);
                    if ("ori_openid error".equals(errMsgDetail)) {
                        logger.warning("openid " + oriOpenid + " 目前没有关注旧账号或from_appid错误");
                    }
                }
            }
        }

        return results;
    }

    /**
     * 保存转换结果到文件
     * @param results 转换结果列表
     */
    private void saveResultsToFile(List<ConversionResult> results) {
        try (FileWriter writer = new FileWriter(OUTPUT_FILE_PATH)) {
            objectMapper.writeValue(writer, results);
            logger.info("Successfully saved " + results.size() + " conversion results to " + OUTPUT_FILE_PATH);
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Failed to save results to file: " + e.getMessage(), e);
        }
    }
    public  void saveResultsJSONToFile(JSONArray input,String filePath) {
        try (FileWriter writer = new FileWriter(filePath)) {
            objectMapper.writeValue(writer, input);
            logger.info("Successfully saved " + input.size() + " conversion results to " + filePath);
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Failed to save results to file: " + e.getMessage(), e);
        }
    }
    /**
     * 打印转换结果
     * @param results 转换结果列表
     */
    private void printResults(List<ConversionResult> results) {
        System.out.println("Conversion Results:");
        for (ConversionResult result : results) {
            System.out.println("Original OpenID: " + result.getOriOpenid());
            System.out.println("New OpenID: " + (result.getNewOpenid() != null ? result.getNewOpenid() : "N/A"));
            System.out.println("Error Message: " + result.getErrMsg());
            System.out.println("------------------------------------");
        }
    }

    /**
     * 转换结果类
     */
    private static class ConversionResult {
        private String oriOpenid;
        private String newOpenid;
        private String errMsg;

        public ConversionResult(String oriOpenid, String newOpenid, String errMsg) {
            this.oriOpenid = oriOpenid;
            this.newOpenid = newOpenid;
            this.errMsg = errMsg;
        }

        // Getter方法
        public String getOriOpenid() {
            return oriOpenid;
        }

        public String getNewOpenid() {
            return newOpenid;
        }

        public String getErrMsg() {
            return errMsg;
        }

        // Setter方法
        public void setOriOpenid(String oriOpenid) {
            this.oriOpenid = oriOpenid;
        }

        public void setNewOpenid(String newOpenid) {
            this.newOpenid = newOpenid;
        }

        public void setErrMsg(String errMsg) {
            this.errMsg = errMsg;
        }
    }
    public  Integer  count(){


        return readOpenidList(OUTPUT_FILE_PATH).size();
    }


    public  void covert(List<UserBinding>  userBindings){

        List<String> openidList = new ArrayList<>();
        userBindings.forEach(userBinding -> openidList.add(userBinding.getOpenId()));
        if (openidList.isEmpty()) {
            logger.warning("No openids found in input file");
            return;
        }
        System.out.println("Total openids: " + openidList.size());
        // 转换openid
        List<ConversionResult> results = this.convertOpenids(openidList);

        // 保存结果到文件
        this.saveResultsToFile(results);


    }
    String nextOpenid=null;
    public List<String> getUserList() throws IOException, InterruptedException {
        HashMap<String, String> moreParams = new HashMap<>();
        moreParams.put("access_token",TOKEN);
        if (nextOpenid != null){
            moreParams.put("next_openid", nextOpenid);
        }

        String response = sendGetRequestWithParams(
                "https://api.weixin.qq.com/cgi-bin/user/get",
                moreParams
        );

        JSONObject parse = JSONObject.parse(response);
        if (parse.getIntValue("errcode")==0){
            JSONObject jsonObject = parse.getJSONObject("data");
            if (jsonObject==null){
                return null;
            }
            JSONArray jsonArray = parse.getJSONObject("data").getJSONArray("openid");
            this.nextOpenid=jsonArray.get(jsonArray.size()-1).toString();
            return jsonArray.toJavaList(String.class);
        }else {
            if (parse.getIntValue("errcode")==41001){
                //getWechatToken();
            }
            return List.of();

        }
    }
    public void getWechatToken(String appid,String secret) {
        try {
            // 带参数和请求头的GET请求
            Map<String, String> headers = Map.of(
                    "User-Agent", "Mozilla/5.0"
            );

            Map<String, String> moreParams = Map.of(
                    "grant_type", "client_credential",
                    "appid", appid,
                    "secret", secret
            );

            String response2 = sendGetRequestWithParams(
                    "https://api.weixin.qq.com/cgi-bin/token",
                    moreParams,
                    headers
            );
            System.out.println("User Info Response: " + response2);
            JSONObject parse = JSONObject.parse(response2);
            TOKEN=parse.getString("access_token");
            System.out.println("TOKEN:"+TOKEN);
        } catch (IOException | InterruptedException e) {
            logger.log(Level.SEVERE, "HTTP GET request with params failed: " + e.getMessage(), e);
        }
    }
    public List<UserBinding> mappingOpenID(List<UserBinding> allUserList) {
        WechatOpenidConverter converter = new WechatOpenidConverter();
        JSONArray jsonArray = converter.readOpenidList(OUTPUT_FILE_PATH);
        HashMap<String, String> map = new HashMap<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            map.put(jsonObject.getString("oriOpenid"),jsonObject.getString("newOpenid"));
        }
        allUserList.forEach(userBinding -> {
            userBinding.setOpenId(map.get(userBinding.getOpenId()));
        });
   /*     JSONArray input = converter.readOpenidList(INPUT_FILE_PATH);
        for (int i = 0; i < input.size(); i++) {
            JSONObject jsonObject = input.getJSONObject(i);
            String openId = jsonObject.getString("open_id");
            String newOpenId = map.get(openId);
            if (StringUtils.isNotBlank(newOpenId)){
                jsonObject.put("open_id",newOpenId);
            }
        }*/

        converter.saveResultsJSONToFile(JSON.parseArray(JSON.toJSONString(allUserList)),OUTPUT_FILE_PATH_JSON);
        return allUserList;
    }
    public void changeDateFormat(){
        JSONArray input = readOpenidList(INPUT_FILE_PATH);
        for (int i = 0; i < input.size(); i++) {
            JSONObject jsonObject = input.getJSONObject(i);
            String createTime = jsonObject.getString("create_time");
            String updateTime = jsonObject.getString("update_time");
  /*          jsonObject.put("create_time", DateUtils.formatDate(createTime));
            jsonObject.put("update_time", DateUtils.formatDate(updateTime))*/;
        }
    }
    /**
     * 主方法
     */
    public  List<String>  getIdList(){
        JSONArray input = readOpenidList(INPUT_FILE_PATH);
        ArrayList<String> strings = new ArrayList<>();
        for (int i = 0; i < input.size(); i++) {
            String openId = input.getJSONObject(i).getString("open_id");
            strings.add(openId);
        }
        return strings;
    }

    public  List<String>  getOutNewId(){
        ArrayList<String> strings = new ArrayList<>();
        try {
            for (int i = 0; i < 4; i++){
                List<String> userList = getUserList();
                if (userList==null){
                    continue;
                }
                List<String> openIds = getIdList();

                for (int j = 0; j < userList.size(); j++) {
                    if (!openIds.contains(userList.get(j))){
                        strings.add(userList.get(j));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return strings ;
    }

    public  List<UserBinding> getAllUserList(){
        MySQLDatabaseConnector dbConnector = new MySQLDatabaseConnector();

        try {
            // 连接数据库
            dbConnector.connect();

            // 查询示例
            System.out.println("=== 查询所有用户 ===");
            return dbConnector.queryUserBindings("SELECT * FROM user_main_binding  where app_id ='wx3d14097dd1c9ee61'");

            // 带参数查询示例
    /*        System.out.println("\n=== 根据ID查询用户 ===");
            dbConnector.queryDataWithParams("SELECT * FROM users WHERE id = ?", 1);*/

        } catch (SQLException e) {
            System.err.println("数据库操作出错: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 关闭连接
            dbConnector.disconnect();
        }
        return null;
    }

    public void writeSQL(List<UserBinding> userBindings) {
        try (FileWriter writer = new FileWriter(OUTPUT_FILE_PATH_SQL)) {
            for (UserBinding userBinding : userBindings) {
                writer.write("INSERT INTO user_main_binding (user_id, old_user_id, union_id, open_id, app_id, wx_name, photo_url, type, last_login_time, create_time, update_time) VALUES (" +
                        userBinding.getUserId() + ", " +
                        userBinding.getOldUserId() + ", '" +
                        userBinding.getUnionId() + "', '" +
                        userBinding.getOpenId() + "', '" +
                        userBinding.getAppId() + "', '" +
                        userBinding.getWxName() + "', '" +
                        userBinding.getPhotoUrl() + "', " +
                        userBinding.getType() + ", '" +
                        userBinding.getLastLoginTime() + "', '" +
                        userBinding.getCreateTime() + "', '" +
                        userBinding.getUpdateTime() + "');"
                        + "\n"
                );
            }
        }catch (IOException e) {
           e.printStackTrace();
        }
    }



    /**
     * 读取OUTPUT_FILE_PATH_JSON的数据，遍历newUserList，收集没有匹配上的openID
     * @param newUserList 新用户ID列表
     * @return 没有匹配上的openID列表
     */
    public List<String> getUnmatchedOpenIds(List<String> newUserList) {
        List<String> unmatchedOpenIds = new ArrayList<>();

        try {
            // 读取OUTPUT_FILE_PATH_JSON文件中的现有数据
            JSONArray jsonArray = readOpenidList(OUTPUT_FILE_PATH_JSON);

            // 创建现有openID集合用于快速查找
            List<String> existingOpenIds = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String openId = jsonObject.getString("open_id");
                if (StringUtils.isNotBlank(openId)) {
                    existingOpenIds.add(openId);
                }
            }

            System.out.println("从文件中读取到 " + existingOpenIds.size() + " 个现有openID");

            // 遍历newUserList，找出没有匹配上的openID
            for (String newOpenId : newUserList) {
                if (StringUtils.isNotBlank(newOpenId) && !existingOpenIds.contains(newOpenId)) {
                    unmatchedOpenIds.add(newOpenId);
                    System.out.println("发现未匹配的openID: " + newOpenId);
                }
            }

            System.out.println("总共找到 " + unmatchedOpenIds.size() + " 个未匹配的openID");

        } catch (Exception e) {
            logger.log(Level.SEVERE, "处理未匹配openID时出错: " + e.getMessage(), e);
        }

        return unmatchedOpenIds;
    }

    /**
     * 读取OUTPUT_FILE_PATH_JSON的数据，遍历newUserList，收集没有匹配上的UserBinding对象
     * @param newUserList 新用户ID列表
     * @return 没有匹配上的UserBinding对象列表
     */
    public List<UserBinding> getUnmatchedUserBindings(List<String> newUserList) {
        List<UserBinding> unmatchedUserBindings = new ArrayList<>();

        try {
            // 读取OUTPUT_FILE_PATH_JSON文件中的现有数据
            JSONArray jsonArray = readOpenidList(OUTPUT_FILE_PATH_JSON);

            // 将JSON数组转换为UserBinding列表
            List<UserBinding> existingUserBindings = new ArrayList<>();
            String jsonString = jsonArray.toJSONString();
            existingUserBindings = objectMapper.readValue(
                    jsonString,
                    new TypeReference<List<UserBinding>>() {}
            );

            // 创建现有openID集合用于快速查找
            List<String> existingOpenIds = new ArrayList<>();
            for (UserBinding userBinding : existingUserBindings) {
                if (userBinding.getOpenId() != null) {
                    existingOpenIds.add(userBinding.getOpenId());
                }
            }

            System.out.println("从文件中读取到 " + existingOpenIds.size() + " 个现有openID");

            // 遍历newUserList，找出没有匹配上的UserBinding
            for (String newOpenId : newUserList) {
                if (StringUtils.isNotBlank(newOpenId) && !existingOpenIds.contains(newOpenId)) {
                    // 创建一个新的UserBinding对象
                    UserBinding newUserBinding = new UserBinding();
                    newUserBinding.setOpenId(newOpenId);
                    unmatchedUserBindings.add(newUserBinding);
                    System.out.println("发现未匹配的openID: " + newOpenId);
                }
            }

            System.out.println("总共找到 " + unmatchedUserBindings.size() + " 个未匹配的UserBinding");

        } catch (Exception e) {
            logger.log(Level.SEVERE, "处理未匹配UserBinding时出错: " + e.getMessage(), e);
        }

        return unmatchedUserBindings;
    }


    public void newDataTOSQL() throws IOException, InterruptedException {
        this.getWechatToken("wx0bd0218a9143a21b", "1bc5506734e25aa34b738925f049981d");
        ArrayList<String> allNewUserIds = new ArrayList<>();

        while(true){
            List<String> newUserList = this.getUserList();
            if (newUserList == null){
                break;
            }
            allNewUserIds.addAll(newUserList);
        }

        System.out.println("总共获取到 " + allNewUserIds.size() + " 个新用户ID");

        if (allNewUserIds.isEmpty()) {
            System.out.println("没有获取到任何新用户ID");
            return;
        }

        FileWriter writer = new FileWriter(OUTPUT_FILE_PATH_SQL);
        try {
            // 修复循环逻辑，正确处理批次
            for (int i = 0; i < allNewUserIds.size(); i += 100) {
                ArrayList<UserBindingRequest> userBindingRequests = new ArrayList<>();

                // 确保不会超出列表范围
                int endIndex = Math.min(i + 100, allNewUserIds.size());

                // 构建当前批次的请求
                for (int j = i; j < endIndex; j++) {
                    UserBindingRequest userBindingRequest = new UserBindingRequest();
                    userBindingRequest.setOpenid(allNewUserIds.get(j));
                    userBindingRequests.add(userBindingRequest);
                }

                System.out.println("开始处理第 " + (i/100 + 1) + " 个批次，包含 " + userBindingRequests.size() + " 个用户");

                String s = this.sendPostRequestBatch(API_BASIC_URL, userBindingRequests, "wx0bd0218a9143a21b");
                JSONObject responseObject = JSON.parseObject(s);

                if (responseObject != null && responseObject.containsKey("user_info_list")) {
                    JSONArray jsonArray = responseObject.getJSONArray("user_info_list");

                    // 写入SQL语句
                    for (int k = 0; k < jsonArray.size(); k++) {
                        JSONObject userBinding = jsonArray.getJSONObject(k);
                        if (userBinding != null) {
                            writer.write("INSERT INTO user_main_binding (user_id, old_user_id, union_id, open_id,app_id) VALUES (" +
                                    "0, " +
                                    "0, '" +
                                    (userBinding.getString("unionid") != null ? userBinding.getString("unionid") : "") + "', '" +
                                    (userBinding.getString("openid") != null ? userBinding.getString("openid") : "") + "', " +
                                    "'wx0bd0218a9143a21b'"+
                                     " ); "
                                    + "\n"
                            );
                        }
                    }
                }

                System.out.println("第 " + (i/100 + 1) + " 个批次处理完成");
            }

        } catch (IOException e) {
            System.err.println("处理过程中发生IO异常: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("处理过程中发生异常: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                System.err.println("关闭文件写入器时发生异常: " + e.getMessage());
            }
        }

        System.out.println("所有数据处理完成");
    }

    public void oldDataToSql(){

        List<UserBinding> allUserList = this.getAllUserList();
        //todo 保留旧的openid
        this.getWechatToken("wx0bd0218a9143a21b","1bc5506734e25aa34b738925f049981d");
        this.covert(allUserList);

        this.mappingOpenID(allUserList);
        this.writeSQL(allUserList);
    }
    public  void getNewUserList(List<String> userBindings) throws IOException, InterruptedException {
        for (String openId : userBindings){
            HashMap<String, String> params = new HashMap<>();
            params.put("access_token",TOKEN);
            params.put("openid",openId);
            String s = this.sendPostRequest(API_BASIC_URL, userBindings,"wx3d14097dd1c9ee61");
            JSONObject jsonObject = JSONObject.parseObject(s);
            FileWriter writer = new FileWriter(OUTPUT_FILE_PATH_NEW_SQL);
            //System.out.println(jsonObject.getString("nickname"));
            writer.write("INSERT INTO user_main_binding (user_id, old_user_id, union_id, open_id ) VALUES (" +
                    0 + ", " +
                    0 + ", '" +
                    jsonObject.getString("unionid") + "', '" +
                    openId + "' ; '") ;


        }

    }
    public static void main(String[] args) throws IOException, InterruptedException {
        /**
         * select  `user_id`, `old_user_id`, `union_id`, `open_id`, `app_id`, `wx_name`, `photo_url`, `type`, `last_login_time`, `create_time`, `update_time` from user_main_binding wx3d14097dd1c9ee61
         * where id  < 284242 and  app_id='wx3d14097dd1c9ee61'
         */
        //旧数据转sql（全量）
        //new WechatOpenidConverter().oldDataToSql();
        //新数据转sql（过滤调重复值）
        new WechatOpenidConverter().newDataTOSQL();


    }
}